package com.example.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-09 08:48
 **/
public class JDBCUtils {
    static Properties prop = null;
    private static String driverClass = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try {
            //如果是tomcat,可以通过getServletContext().getRealPath()来
            //通过 src/main/resources/config.properties
            //这是一个查询文件的好方法,在src下面都可以用这个方法,如果是工程路径下的就不行
            InputStream ras = JDBCUtils.class.getClassLoader()
                    .getResourceAsStream("config.properties");
            prop = new Properties();
            prop.load(ras);

            //
            driverClass = prop.getProperty("driverClass");

            //
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");

            //加载驱动程序
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return con;
    }

    public static void close(Connection con, Statement stat) {
        close(con, stat, null);
    }

    public static void close(Connection con, Statement stat, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
